package com.frkj.yuan.fragment.my;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.frkj.yuan.R;
import com.frkj.yuan.activity.JiuZhengPesonalActivity;
import com.frkj.yuan.activity.MyCardActivity;
import com.frkj.yuan.activity.MyDianPingActivity;
import com.frkj.yuan.activity.RecruitAccompanyingMemberActivity;
import com.frkj.yuan.activity.StoredMoneyActivity;
import com.frkj.yuan.activity.TuijianPriendActivity;
import com.frkj.yuan.activity.UserLoginActivity;
import com.frkj.yuan.activity.UserPersonalActivity;
import com.frkj.yuan.activity.UserSettingActivity;
import com.frkj.yuan.activity.YouhuiQuanListActivity;
import com.frkj.yuan.api.bean.UserInforMsgBean;
import com.frkj.yuan.api.category.UserInforMsgCategory;
import com.frkj.yuan.api.presenter.UserInforMsgPresenter;
import com.frkj.yuan.base.BaseFragment;
import com.frkj.yuan.dialog.LoginOutDialog;
import com.frkj.yuan.dialog.OnQuiteDialogClickListener;
import com.frkj.yuan.dialog.RoundCornerDialog;
import com.frkj.yuan.dialog.RoundKefuDialog;
import com.frkj.yuan.main.ConstantStaticUrl;
import com.frkj.yuan.utils.GlideCacheUtil;
import com.frkj.yuan.utils.HttpNetworkConnectUtils;
import com.frkj.yuan.utils.SPUtils;
import com.frkj.yuan.utils.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.io.ByteArrayInputStream;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

import static android.content.Context.MODE_PRIVATE;

/**
 * 作者：菲菲 on 2022/2/11 11:23
 * company：丰蓉信息科技有限公司
 */
public class MyFragment extends BaseFragment implements UserInforMsgCategory.View {
    @BindView(R.id.user_mobile)
    TextView mUserMobile;
    @BindView(R.id.user_name)
    TextView mUserName;
    @BindView(R.id.icon_my)
    CircleImageView mIconImage;
    @BindView(R.id.no_login)
    TextView mNoLogin;
    @BindView(R.id.my_person)
    LinearLayout mLinearPerson;
    private UserInforMsgPresenter mPresenter;
    private long mUserId;
    private String mIconAvatar, mUserPhone, mUserNickName, mToken, mUser_Name, mSfzCardId;
    private LoginOutDialog dialog;

    @Override
    public int getLayoutResource() {
        return R.layout.fragment_my_view;
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.getUserInforMsg(mToken, mUserId);
    }
    // TODO: 2022/6/8 fragment 来回切换自动刷新列表数据
    @Override
    public void onHiddenChanged(boolean hidden) {
        // TODO Auto-generated method stub
        super.onHiddenChanged(hidden);
        if (!hidden) {
            mPresenter.getUserInforMsg(mToken, mUserId);
        }
    }
    @Override
    public void initLayoutView() {
        mToken = (String) SPUtils.get(getActivity(), ConstantStaticUrl.mToken, "");
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("First", MODE_PRIVATE);
        mUserId = sharedPreferences.getLong(ConstantStaticUrl.userId, 0);
        mPresenter = new UserInforMsgPresenter(this);
        SetPersenter(mPresenter);
        if (!HttpNetworkConnectUtils.isNetworkConnected(getActivity())) {
            ToastUtil.showToastINFO(getActivity(), "网络未连接,请确保网络通畅");
        } else {
            mPresenter.getUserInforMsg(mToken, mUserId);
        }
    }

    @OnClick({R.id.chizhijin, R.id.youhuiquan, R.id.kuzhong_my, R.id.no_login, R.id.tjhy_my_item, R.id.my_person, R.id.my_setting, R.id.my_jiuzhen, R.id.card_my, R.id.my_dianping, R.id.my_zhaomu})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.chizhijin:
                openActivityWitchAnimation(StoredMoneyActivity.class);
                break;
            case R.id.my_person:
                Intent intent = new Intent(getActivity(), UserPersonalActivity.class);
                intent.putExtra("mobile", mUserPhone);
                intent.putExtra("nickName", mUserNickName);
                intent.putExtra("iconImage", mIconAvatar);
                intent.putExtra("name", mUser_Name);
                intent.putExtra("mSfzCardId", mSfzCardId);
                intent.putExtra("stateType", "0");
                startActivityForResult(intent, 100);
                break;
            case R.id.youhuiquan:
                openActivityWitchAnimation(YouhuiQuanListActivity.class);
                break;
            case R.id.no_login:
                openActivityWitchAnimation(UserLoginActivity.class);
                SPUtils.clear(getActivity());
                getActivity().finish();
                break;
            case R.id.my_jiuzhen:
                openActivityWitchAnimation(JiuZhengPesonalActivity.class);
                break;
            case R.id.my_dianping:
                openActivityWitchAnimation(MyDianPingActivity.class);
                break;
            case R.id.my_zhaomu:
                openActivityWitchAnimation(RecruitAccompanyingMemberActivity.class);
                break;
            case R.id.card_my:
                openActivityWitchAnimation(MyCardActivity.class);
                break;
            case R.id.tjhy_my_item:
                openActivityWitchAnimation(TuijianPriendActivity.class);
                break;
            case R.id.my_setting:
                openActivityWitchAnimation(UserSettingActivity.class);
                break;
            case R.id.kuzhong_my:
                RoundKefuDialog dialog = new RoundKefuDialog(getActivity());
                dialog.show();
                TextView mobile = dialog.findViewById(R.id.mobile_number);
                mobile.setText("0931-8797777");
                dialog.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                dialog.findViewById(R.id.tv_confirm).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        // 检查是否获得了权限
                        if (ContextCompat.checkSelfPermission(getActivity(),
                                Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                            // 若没有获得授权，申请授权
                            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                                    Manifest.permission.CALL_PHONE)) {
                                // 如果app之前请求过该权限,被用户拒绝, 这个方法就会返回true.
                                //  如果用户之前拒绝权限的时候勾选了对话框中”Don’t ask again”的选项,那么这个方法会返回false.
                                // 如果设备策略禁止应用拥有这条权限, 这个方法也返回false.
                                // 弹窗需要解释为何需要该权限，再次请求授权
                                // 帮跳转到该应用的设置界面，让用户手动授权
                                Intent call = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
                                call.setData(uri);
                                startActivity(call);
                            } else {
                                // 不需要解释为何需要该权限，直接请求授权
                                ActivityCompat.requestPermissions(getActivity(),
                                        new String[]{Manifest.permission.CALL_PHONE},
                                        0);
                            }
                        } else {
                            // 已经获得授权，可以打电话
                            // 通过intent跳转到拨打电话的界面
                            Intent intent1 = new Intent();
                            intent1.setAction(Intent.ACTION_CALL);
                            Uri phoneNum = Uri.parse("tel:" + "0931-8797777");
                            intent1.setData(phoneNum);
                            startActivity(intent1);
                        }
                        dialog.dismiss();
                    }

                });
                break;
        }
    }

    @Override
    public void getUserInforMsg(UserInforMsgBean userinfor) {
        if (userinfor.getCode() == ConstantStaticUrl.SUCCESS_CODE) {
            mNoLogin.setVisibility(View.GONE);
            mLinearPerson.setVisibility(View.VISIBLE);
            if (userinfor.getData() != null) {
                mIconAvatar = userinfor.getData().getAvatar();
                RequestOptions requestOptions = new RequestOptions();
                requestOptions.error(R.drawable.logo_circler_bg)
                        .circleCrop()
                        .skipMemoryCache(true)
                        .diskCacheStrategy(DiskCacheStrategy.NONE);
                Glide.with(getActivity())
                        .load(userinfor.getData().getAvatar())
                        .apply(requestOptions)
                        .into(mIconImage);
                if (userinfor.getData().getNickName() != null || userinfor.getData().getMobile() != null) {
                    mUserPhone = userinfor.getData().getMobile();
                    mUserNickName = userinfor.getData().getNickName();
                    mUser_Name = userinfor.getData().getRealName();
                    mSfzCardId = userinfor.getData().getIdCard();
                    mUserMobile.setText("手机号码 : " + mUserPhone);
                    mUserName.setText(mUserNickName);
                } else {
                    mUserMobile.setText("");
                    mUserName.setText("");
                }
            }
        } else if (userinfor.getCode() == 401) {
            mNoLogin.setVisibility(View.VISIBLE);
            mLinearPerson.setVisibility(View.GONE);
            if (dialog == null) {
                dialog = new LoginOutDialog(getActivity());
            }
            if (dialog != null && !dialog.isShowing()) {
                dialog.show();
            }
            dialog.findViewById(R.id.circler_delete).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            dialog.findViewById(R.id.to_login).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openActivityWitchAnimation(UserLoginActivity.class);
                    SPUtils.clear(getActivity());
                    getActivity().finish();
                    dialog.dismiss();
                }
            });
            dialog.show();
        } else {
            ToastUtil.showToastINFO(getActivity(), userinfor.getMsg());
        }
    }

    @Override
    public void SetPersenter(Object persenter) {
    }

    @Override
    public void OnShowErrorMsg(String mErrorMsg) {
        ToastUtil.showToastERROR(getActivity(), mErrorMsg);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 100 && resultCode == 200) {
            String nickName = data.getStringExtra("nickName");
            String iconImage = data.getStringExtra("iconImage");
            mUserName.setText(nickName);
            GlideCacheUtil.getInstance().clearImageAllCache(getActivity());
            RequestOptions requestOptions = new RequestOptions();
            requestOptions.error(R.drawable.head_icon)
                    .circleCrop()
                    .skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.NONE);
            Glide.with(getActivity())
                    .load(iconImage)
                    .apply(requestOptions)
                    .into(mIconImage);
        }
    }
}
